package tjs.study.notes.dotest.zookper.locker.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Random;
import java.util.concurrent.CountDownLatch;

/**
 * Created by Nicky.Tang on 2021/11/10 12:08 下午
 *
 * @since 02.12.10
 */
public class TestLockCommon {
    private static final Logger logger = LoggerFactory.getLogger(TestLockCommon.class);


    public static void doTest(RLockFactory rLockFactory, String orderId, int num) throws InterruptedException {
        CountDownLatch countDownLatchMake = new CountDownLatch(num);
        CountDownLatch countDownLatchFinsh = new CountDownLatch(num);

        for (int i = 0; i < num; i++) {
            new Thread(() -> {
                try {
                    countDownLatchMake.await();// 等待countDownLatch为0
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                RLock rLock = rLockFactory.getLock(orderId);
                rLock.lock();
                logger.info("{} 成功持有锁，开始执行业务。。。", rLock.getLockPath());
                try {
                    Thread.currentThread().sleep(new Random().nextInt(10) * 300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                logger.info("{} 开始释放锁，已结束执行业务。。。", rLock.getLockPath());
                rLock.unlock();
                countDownLatchFinsh.countDown();
            }).start();
            countDownLatchMake.countDown();//减1
        }
        countDownLatchFinsh.await();
    }
}
